package com.sita.bike.ui.activity.roadtrust;

/**
 * Created by new on 2015/11/15.
 */

import android.app.Activity;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bigkoo.convenientbanner.CBViewHolderCreator;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.OnItemClickListener;
import com.sita.bike.R;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Picture;
import com.sita.bike.rest.model.ResourceFetchParams;
import com.sita.bike.rest.model.ResourceFetchResponse;
import com.sita.bike.ui.view.NetworkImageHolderView;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.BitmapUtils;
import com.sita.bike.utils.MediaManager;
import com.sita.bike.utils.RetrofitUtils;

import java.util.ArrayList;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class RoadTrustMessagePopupActivity extends Activity implements OnItemClickListener, ViewPager.OnPageChangeListener {
    private RelativeLayout layout;
    private String mResourceId;
    private Bitmap mHeader;
    private ImageView mImageViewHeader;
    private ImageView mImageButtonPlay;
    private List<String> mPics;
    private String mAudioUrl = "";
    private ConvenientBanner convenientBanner;
    private List<String> networkImages;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mResourceId = getIntent().getStringExtra("resource");
        mHeader = BitmapUtils.bytesToBitmap(getIntent().getByteArrayExtra("header"));
        initViews();
        fetchResource();
    }

    private void initBanner() {
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, networkImages)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});

    }

    private void initViews() {
        setContentView(R.layout.activity_roadtrust_message);
        layout = (RelativeLayout) findViewById(R.id.activity_roadtrust_message_layout);
        layout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "提示：点击窗口外部关闭窗口！",
                        Toast.LENGTH_SHORT).show();
            }
        });
        convenientBanner = (ConvenientBanner) findViewById(R.id.activity_roadtrust_message_banner);
        mImageViewHeader = (ImageView) findViewById(R.id.road_trust_message_header);
        mImageViewHeader.setImageBitmap(mHeader);
        mImageButtonPlay = (ImageView) findViewById(R.id.road_trust_message_play_button);
        mImageButtonPlay.setVisibility(View.INVISIBLE);
        mImageButtonPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //play audio
                if (mAudioUrl.equals("")) {
                    Toast.makeText(getApplicationContext(), "声音尚未加载成功，请稍后",
                            Toast.LENGTH_SHORT).show();
                } else {
                    MediaManager.playSound(mAudioUrl, new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            //
                        }
                    });
                }
            }
        });
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        finish();
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //开始自动翻页
        convenientBanner.startTurning(5000);
        //此值不能小于1200（即ViewPagerScroller的mScrollDuration的值），
        // 否则最后一页翻页效果会出问题。
        // 如果硬要兼容1200以下，
        // 那么请修改ViewPagerScroller的mScrollDuration的值，
        // 不过修改后，3d效果就没那么明显了。
    }

    @Override
    protected void onPause() {
        super.onPause();
        //停止翻页
        convenientBanner.stopTurning();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onPageSelected(int position) {
        Toast.makeText(this, "监听到翻到第" + position + "了", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(int position) {
        Toast.makeText(this, "点击了第" + position + "个", Toast.LENGTH_SHORT).show();
    }

    // Get the resource list
    private void fetchResource() {

        ResourceFetchParams rfp = new ResourceFetchParams();
        rfp.mAccountId = AccountUtils.getAccountID();
        rfp.mResourceId = mResourceId;

        RestClient.getRestNormalService().fetchOneResource(rfp, new Callback<ResourceFetchResponse>() {
            @Override
            public void success(ResourceFetchResponse resourceFetchResponse, Response response) {
                if (response.getStatus() == 200 &&
                        resourceFetchResponse.mErrorCode.equals("0") &&
                        resourceFetchResponse.mData != null) {
                    if (mPics == null) {
                        mPics = new ArrayList<String>();
                    }
                    mPics.clear();
                    for (Picture pics : resourceFetchResponse.mData.mPics
                            ) {
                        mPics.add(pics.mUrl);
                    }

                    if (resourceFetchResponse.mData.mAudio.size() > 0) {
                        mAudioUrl = resourceFetchResponse.mData.mAudio.get(0).mUrl;
                        if (mAudioUrl != null && !mAudioUrl.equals("")) {
                            mImageButtonPlay.setVisibility(View.VISIBLE);
                        }
                    }

                    Toast.makeText(getApplicationContext(), getResources().getText(R.string.load_ok), Toast.LENGTH_LONG).show();

                    if (mPics.size() > 0) {
                        networkImages = mPics;
                        initBanner();
//                        convenientBanner.notifyDataSetAdd();
                    }
                }
                Log.d("response", response.getReason());
            }

            @Override
            public void failure(RetrofitError error) {
                RetrofitUtils.displayError(RoadTrustMessagePopupActivity.this, error);
                Log.d("response", error.getMessage());
            }
        });
    }

}